/*
 * @Author: saber
 * @Date: 2021-11-02 16:59:46
 * @LastEditTime: 2022-07-14 14:30:30
 * @LastEditors: mayijun
 * @Description: 针对请求结果的处理
 */
import { ElMessage } from 'element-plus/lib/index';
import { Message } from '@arco-design/web-vue';
const defalutIsSuccess = (data: any) => data.code === 0 || false;
export const CODE_ERROR = 'codeError';
export const RESPONSE_ERROR = 'responsEerror';
export default (_context?: any) => {
  const name = 'responseHandler';
  const requestSuccess = (config: any) => {
    return config;
  };
  const requestError = (error: any) => {
    return Promise.reject(error);
  };
  // 如果要用到this就不能使用 箭头函数
  const responseSuccess = function (
    this: {
      name: string;
      requestSuccess: (config: any) => any;
      requestError: (error: any) => Promise<never>;
      responseSuccess: (response: any) => any;
      responseError: (error: any) => Promise<never>;
    },
    response: any
  ) {
    const { data, config } = response;
    const isSuccess = config[name]?.isSuccess || defalutIsSuccess;
    if (data && isSuccess(data)) {
      console.log(config);
      // return data;
    } else {
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      if (data?.code === 400) {
        let msg = data?.msg;
        //如果有具体信息展示具体错误
        if (Array.isArray(data?.data)) {
          let errorArray = data?.data.map((item: any) => item.error_msg);
          let errorStr = errorArray.join("、");
          msg = msg + ":" + errorStr;
        }
        Message.warning(msg);
        // ElMessage.warning(msg);
      }

      (this as any).emit(CODE_ERROR, data);
    }
    return data;
  };
  const responseError = function (
    this: {
      name: string;
      requestSuccess: (config: any) => any;
      requestError: (error: any) => Promise<never>;
      responseSuccess: (
        this: {
          name: string;
          requestSuccess: (config: any) => any;
          requestError: (error: any) => Promise<never>;
          responseSuccess: (response: any) => any;
          responseError: (error: any) => Promise<never>;
        },
        response: any
      ) => any;
      responseError: (error: any) => Promise<never>;
    },
    error: any
  ) {
    // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    // @ts-ignore
    if (error?.code === 500) Message.error('服务器端错误');
    (this as any).emit(RESPONSE_ERROR, error);
    return Promise.reject(error);
  };
  return {
    name,
    requestSuccess,
    requestError,
    responseSuccess,
    responseError
  };
};
